package com.dk.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

	@RequestMapping("upload")
	@ResponseBody
	public Map<String,String> upload(@RequestParam(value = "myFile") MultipartFile myFile) {
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		String endpoint = "http://oss-cn-beijing.aliyuncs.com";
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = "LTAI4Fz7e5aqwbXHSqS7grS8";
		String accessKeySecret = "qsIhqBLuWDiSiOpcEb8vU6l3Bc7i8z";
		String bucketName = "dongdongshop-1905-dyn";
	// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
		String fileName = myFile.getOriginalFilename();
		fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
		String objectName =fileName;

	// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
	//		String content = "Hello OSS";

		Map<String,String> map = new HashMap<>();
		try {
			ossClient.putObject(bucketName, objectName, myFile.getInputStream());
			String url = "https://dongdongshop-1905-dyn.oss-cn-beijing.aliyuncs.com/"+objectName;
			map.put("imgUrl",url);
		} catch (IOException e) {
			e.printStackTrace();
		}

	// 关闭OSSClient。
		ossClient.shutdown();
		return map;
	}
}
